import axios from "axios";
const state = {
  shoppingCart: [],
};

const mutations = {
  setShoppingCart(state, data) {
    // 设置购物车状态
    state.shoppingCart = data;
    // this.timer = setTimeout(() => {
    //   this.$router.go(0);
    // }, 100);
  },
  unshiftShoppingCart(state, data) {
    // 添加购物车
    // 用于在商品详情页点击添加购物车,后台添加成功后，更新vuex状态
    state.shoppingCart.unshift(data);
  },
  addShoppingCartNum(state, data) {
    // 增加购物车商品数量
    // 用于在商品详情页点击添加购物车,后台返回002，“该商品已在购物车，数量 +1”，更新vuex的商品数量
    state.shoppingCart.unshift(data);
  },
};

const actions = {
  setShoppingCart({ commit }) {
    // console.log(111);
    let user = JSON.parse(sessionStorage.getItem("user" || "{}"));
    // console.log(user.id);
    if (user) {
      axios
        .get(`http://10.41.9.94:8888/ShoppingCart?user_id=${user.id}`)
        .then((res) => {
          commit("setShoppingCart", res.data);
        });
    } else {
      commit("setShoppingCart", []);
    }
  },
  unshiftShoppingCart({ commit }, data) {
    commit("unshiftShoppingCart", data);
  },
  addShoppingCartNum({ commit }, data) {
    commit("addShoppingCartNum", data);
  },
};

const getters = {
  getShoppingCart(state) {
    // 获取购物车状态
    return state.shoppingCart;
  },
  getNum(state) {
    // 购物车商品总数量
    let totalNum = 0;
    totalNum = state.shoppingCart.length;
    return totalNum;
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
